package com.dragonfly.shutter.utils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 使用html格式发送邮件
 * @author 金灵杰
 *
 */
public class SendMail {
	private String from;
	private JavaMailSender sender;
	
	/**
	 * 构造函数
	 * 获得应用程序上下文，加载mailSender
	 */
	public SendMail()
	{

	}
	
	/**
	 * 设置发送方邮件地址
	 * @param from 从配置文件中注入的发送方地址
	 */
	public void setFrom(String from) {
		this.from = from;
	}

	/**
	 * 获得发送方邮件地址
	 * @return 发送者的邮件地址
	 */
	public String getFrom() {
		return from;
	}

	/**
	 * @param sender the sender to set
	 */
	public void setSender(JavaMailSender sender) {
		this.sender = sender;
	}

	/**
	 * @return the sender
	 */
	public JavaMailSender getSender() {
		return sender;
	}

	/**
	 * 发送邮件
	 * @param sendTo 邮件接收方
	 * @param subject	 邮件主题
	 * @param text 邮件正文（html格式）
	 */
	public void send(String sendTo, String subject, String text)
	{
		MimeMessage message = sender.createMimeMessage();	
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");
			messageHelper.setFrom(from);
			messageHelper.setTo(sendTo);
			messageHelper.setSubject(subject);
			messageHelper.setText(text, true);
			
			sender.send(message);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
